package com.by.yz.chatuidemo.ui;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.android.volley.toolbox.NetworkImageView;
import com.bumptech.glide.Glide;
import com.by.yz.App;
import com.by.yz.Register.DoctorREST;
import com.by.yz.custom.CircleNetworkImageView;
import com.by.yz.entity.Doctorbean;
import com.by.yz.entity.Image;
import com.by.yz.entity.UserTest;
import com.by.yz.loginUtil.ImageRESTful;
import com.by.yz.loginUtil.UserRESTFul;
import com.by.yz.mypersonal.PersonalImproveInfoActivity;
import com.by.yz.mypersonal.PersonalUpdateInfoActivity;
import com.by.yz.util.ToJSonObject;
import com.by.yz.R;
import com.hyphenate.easeui.utils.EaseUserUtils;
import com.hyphenate.easeui.widget.EaseAlertDialog;
import com.yancy.imageselector.ImageConfig;

import android.Manifest;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.yancy.imageselector.ImageSelector;
import com.yancy.imageselector.ImageSelectorActivity;

import org.json.JSONException;
import org.json.JSONObject;

/**
 *　　　　　　　　┏┓　　　┏┓+ +
 *　　　　　　　┏┛┻━━━┛┻┓ + +
 *　　　　　　　┃　　　　　　　┃ 　
 *　　　　　　　┃　　　━　　　┃ ++ + + +
 *　　　　　　  ████━████  +
 *　　　　　　　┃　　　　　　　┃ +
 *　　　　　　　┃　　　┻　　　┃
 *　　　　　　　┃　　　　　　　┃ + +
 *　　　　　　　┗━┓　　　┏━┛
 *　　　　　　　　　┃　　　┃　　　　　　　　　　　
 *　　　　　　　　　┃　　　┃ + + + +
 *　　　　　　　　　┃　　　┃　　　　Code is far away from bug with the animal protecting　　　　　　　
 *　　　　　　　　　┃　　　┃ + 　　　　神兽保佑,代码无bug　　
 *　　　　　　　　　┃　　　┃
 *　　　　　　　　　┃　　　┃　　+　　　　　　　　　
 *　　　　　　　　　┃　 　　┗━━━┓ + +
 *　　　　　　　　　┃ 　　　　　　　┣┓
 *　　　　　　　　　┃ 　　　　　　　┏┛
 *　　　　　　　　　┗┓┓┏━┳┓┏┛ + + + +
 *　　　　　　　　　　┃┫┫　┃┫┫
 *　　　　　　　　　　┗┻┛　┗┻┛+ + + +
 /**
 * Created by 正和守护者 on 2020/12/20.
 */

public class UserProfileActivity extends com.by.yz.activity.base.BaseActivity implements OnClickListener{

	private CircleNetworkImageView headAvatar;
	private ImageView iconRightArrow,iconRightArrow1;
	private TextView tvNickName;
	private TextView tvUsername;
	private TextView sex;
	private RelativeLayout rlNickName,setSex,layoutAvatar,pcMore;
	private Button pop,xiangce;
	private View vis;
	UserTest userTest;
	Doctorbean getdt;
	private Bitmap bitmap;
	private ProgressDialog dialog;
	private ImageConfig imageConfig;
	private boolean ImageSelected=false;
	private String imageurl;
	private ArrayList<String> path = new ArrayList<>();
	private String username;
	boolean enableUpdate;
	private Toast toast = null;
	final int requestCodeCameraStorage = 100;

	@Override
	protected void onCreate(Bundle arg0) {
		Log.e("-----onCreate-----","success");
		super.onCreate(arg0);
		setContentView(R.layout.em_activity_user_profile);
		setToolbarTitle("个人资料");
		initView();
		initListener();
	}

	@Override
	protected void onRestart(){
		super.onRestart();
		Log.e("-----onRestart-----","success");
		initView();
		initListener();
	}

	private void initView() {
		Log.e("-----initView-----","success");
		imageConfig  = new ImageConfig.Builder(new GlideLoader())
				.steepToolBarColor(getResources().getColor(R.color.colorPrimary))
				// 标题的背景颜色
				.titleBgColor(getResources().getColor(R.color.colorPrimary))
				// 提交按钮字体的颜色
				.titleSubmitTextColor(getResources().getColor(R.color.white))
				// 标题颜色
				.titleTextColor(getResources().getColor(R.color.white))
				// (截图默认配置：关闭    比例 1：1    输出分辨率  500*500)
				.crop(1, 1, 500, 500)
				// 开启单选   （默认为多选）
				.singleSelect()
				.pathList(path)
				// 开启拍照功能 （默认关闭）
				.showCamera()
				// 拍照后存放的图片路径（默认 /temp/picture） （会自动创建）
				.filePath("/ImageSelector/Pictures")
				.build();

		headAvatar = (CircleNetworkImageView) findViewById(R.id.user_head_avatar);
		headAvatar.setDefaultImageResId(R.mipmap.login_logo1);
		headAvatar.setErrorImageResId(R.mipmap.login_error);
//		headAvatar.setImageUrl("http://img2.hao661.com/uploads/allimg/c150515/1431E91Z5M10-2194c1.jpg",App.imageLoader);
		tvUsername = (TextView) findViewById(R.id.user_username);
		tvNickName = (TextView) findViewById(R.id.user_nickname);
		rlNickName = (RelativeLayout) findViewById(R.id.rl_nickname);
		layoutAvatar = (RelativeLayout) findViewById(R.id.layout_avatar);
		pcMore = (RelativeLayout) findViewById(R.id.pc_more);
		setSex=(RelativeLayout) findViewById(R.id.pc_sex);
		iconRightArrow = (ImageView) findViewById(R.id.ic_right_arrow);
		iconRightArrow1 = (ImageView) findViewById(R.id.ic_right_arrow1);
		sex = (TextView) findViewById(R.id.sex1);
		vis = findViewById(R.id.ll_popup);
		pop = (Button) findViewById(R.id.item_popupwindows_cancel);
		pop.setOnClickListener(this);
		xiangce=(Button)findViewById(R.id.item_popupwindows_Photo);
		xiangce.setOnClickListener(this);
		Intent intent = getIntent();
		username = intent.getStringExtra("username");
		tvUsername.setText(username);
		UserRESTFul userRESTFul=new UserRESTFul();
		userRESTFul.getUser(username, new UserRESTFul.UserPOSTCallBack() {
			@Override
			public void ok(JSONObject response) throws JSONException {
				JSONObject jsonObject=response;
				userTest=ToJSonObject.jsonToBean(jsonObject.toString(),UserTest.class);
				tvNickName.setText(userTest.getnickName());
				if(userTest.getsex()){
					sex.setText("男");
				}else{
					sex.setText("女");
				}
				if(userTest.getHeadimg()!=null){
					headAvatar.setImageUrl(userTest.getHeadimg(), App.imageLoader);
				}
			}
			@Override
			public void error(String response) {
				Log.e("PEActivity-user-failed","获取用户表失败"+response);
			}
		});
	}

	private void initListener() {
		Log.e("-----initListener-----","success");
		Intent intent = getIntent();
		enableUpdate = intent.getBooleanExtra("setting", false);
		pcMore.setOnClickListener(this);
		if (enableUpdate) {
			iconRightArrow.setVisibility(View.VISIBLE);
			iconRightArrow1.setVisibility(View.VISIBLE);
			setSex.setOnClickListener(this);
			layoutAvatar.setOnClickListener(this);
			vis.setOnClickListener(this);
			pcMore.setOnClickListener(this);
			rlNickName.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					Log.e("-----rlNickName-----",userTest.getnickName());
					Context context = view.getContext();
					Intent intent=new Intent(context,PersonalUpdateInfoActivity.class);
					Bundle bundle=new Bundle();
					bundle.putSerializable("user1",userTest);
					intent.putExtras(bundle);
					context.startActivity(intent);
				}
			});
		} else {
			iconRightArrow.setVisibility(View.INVISIBLE);
			iconRightArrow1.setVisibility(View.INVISIBLE);
		}
		if(username != null){
			EaseUserUtils.setUserNick(username, tvNickName);
			EaseUserUtils.setUserAvatar(this, username, headAvatar);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.layout_avatar:
				vis.setVisibility(View.VISIBLE);
				vis.setOnClickListener(null);
				break;
			case R.id.pc_sex:
				final AlertDialog.Builder builder = new AlertDialog.Builder(UserProfileActivity.this); //定义选择性别对话框
				final String[] strarr = {"男", "女"};
				builder.setItems(strarr, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface arg0, int arg1) {
						boolean sex1 = true;//性别默认男
						sex.setText("男");
						if (arg1 == 1) {//女
							sex1 = false;
							sex.setText("女");
						}
						if(sex1!=userTest.getsex()) {
							userTest.setsex(sex1);
							JSONObject jsonObject = ToJSonObject.beanToJSONObejct(userTest);
							UserRESTFul userRESTFul = new UserRESTFul();
							userRESTFul.putUser(jsonObject, new UserRESTFul.UserPOSTCallBack() {
								@Override
								public void ok(JSONObject response) throws JSONException {
									Toast.makeText(getApplicationContext(), "修改性别成功", Toast.LENGTH_SHORT).show();
								}
								@Override
								public void error(String response) {
									Toast.makeText(getApplicationContext(), "修改性别失败，请检查网络", Toast.LENGTH_SHORT).show();
								}
							});
						}
					}
				});
				builder.show();
				break;
			case R.id.item_popupwindows_cancel:
				vis.setVisibility(View.GONE);
				break;
			case R.id.item_popupwindows_Photo:
				//判断Android版本是否大于23
//				Log.e("存储权限",ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)+"");
//				Log.e("相机权限",ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.CAMERA)+"");
				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
					int checkStoragePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
					int checkCameraPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);

					if (checkStoragePermission != PackageManager.PERMISSION_GRANTED ||
							checkCameraPermission != PackageManager.PERMISSION_GRANTED){
						ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA},
								requestCodeCameraStorage);
						return;
					}else{
						path.clear();
						ImageSelector.open(UserProfileActivity.this, imageConfig);   // 开启图片选择器
					}
				}else{
						path.clear();
						ImageSelector.open(UserProfileActivity.this, imageConfig);   // 开启图片选择器
				}
				break;
			case R.id.pc_more:
				Intent intent = new Intent(UserProfileActivity.this, PersonalImproveInfoActivity.class);
				intent.putExtra("username",userTest.getPhonenumber());
				intent.putExtra("setting", enableUpdate);
				Bundle bundle=new Bundle();
				bundle.putSerializable("user",userTest);
				intent.putExtras(bundle);
				startActivity(intent);
				break;
			default:
				break;
		}
	}

	/**
	 * 注册权限申请回调
	 * @param requestCode 申请码
	 * @param permissions 申请的权限
	 * @param grantResults 结果
	 */
	@Override
	public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){
		switch (requestCode){
			case  requestCodeCameraStorage:
				if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED){
					path.clear();
					ImageSelector.open(UserProfileActivity.this, imageConfig);   // 开启图片选择器
				}else{
					if(!ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)){
						new EaseAlertDialog(this, "存储权限被禁止，请开启权限后重试").show();
					}else if(!ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.CAMERA)){
						new EaseAlertDialog(this, "相机权限被禁止，请开启权限后重试").show();
					}else{
						new EaseAlertDialog(this, "相机或存储权限被禁止，请开启权限后重试").show();
					}
				}
				break;
			default:
				super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.e("--onActivityResult--","start");
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == ImageSelector.IMAGE_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
			// Get Image Path List
			List<String> pathList = data.getStringArrayListExtra(ImageSelectorActivity.EXTRA_RESULT);
			path.clear();
			path.addAll(pathList);
			if(path.size()!=0){
				ImageSelected=true;
				Log.e("s",pathList.get(0));
				setPicToView(path.get(path.size()-1));
			}else{
				ImageSelected=false;
			}
		}
	}

	/**
	 * save the picture data
	 *
	 * @param data
	 */
	private void setPicToView(String data)  {
		Log.e("--setPicToView--","start");
		bitmap= BitmapFactory.decodeFile(data);
		upImage(data);
		Log.e("--setPicToView--","end");
	}

	public void upImage(final String data){
		Log.e("--upImage--","stat");
		dialog = ProgressDialog.show(this, getString(R.string.dl_update_photo), getString(R.string.dl_waiting));
		new Thread(new Runnable() {
			@Override
			public void run() {
				Log.e("upImageThread1","start");
				BitmapFactory.Options options = new BitmapFactory.Options();
				options.inSampleSize = 1;
				Bitmap img = BitmapFactory.decodeFile(data, options);
				String str = bitmapToBase64(img);//将图片进行压缩
				Image a = new Image(str, ToJSonObject.getFileName(data));
				JSONObject articleImage = ToJSonObject.beanToJSONObejct(a);
				ImageRESTful imageRESTful=new ImageRESTful();
				imageRESTful.postImages(articleImage, new ImageRESTful.MyPostCallBack() {
					@Override
					public void ok(JSONObject response) throws JSONException {
						Log.e("s",response.toString());
						String imageUrl = response.getString("link");
						imageurl  = imageUrl.replace("]", "/");
						Log.e("---imageurl---",imageurl);
						saveAvatar();
					}
					@Override
					public void error(String error) {}

				});
				Log.e("upImageThread1","end");
			}
		}).start();
		dialog.show();
		Log.e("--upImage--","end");
	}

	public void saveAvatar(){

		userTest.setHeadimg(imageurl);
		JSONObject jsonObject = ToJSonObject.beanToJSONObejct(userTest);
		UserRESTFul userRESTFul = new UserRESTFul();
		userRESTFul.putUser(jsonObject, new UserRESTFul.UserPOSTCallBack() {
			@Override
			public void ok(JSONObject response) throws JSONException {
				dialog.dismiss();
				Toast.makeText(getApplicationContext(), "头像修改成功", Toast.LENGTH_SHORT).show();
				UserProfileActivity.this.finish();
			}
			@Override
			public void error(String response) {
				dialog.dismiss();
				Toast.makeText(getApplicationContext(), "头像修改失败", Toast.LENGTH_SHORT).show();
			}
		});

	}

//	public Doctorbean findDoctor(String userTest){
//
//		DoctorREST doctorREST =new DoctorREST();
//		doctorREST.getDoctorRESTo();
//		return null ;
//	}

	public class GlideLoader implements com.yancy.imageselector.ImageLoader {

		@Override
		public void displayImage(Context context, String path, ImageView imageView) {
			Glide.with(context)
					.load(path)
					.placeholder(com.yancy.imageselector.R.mipmap.imageselector_photo)
					.centerCrop()
					.into(imageView);
		}
	}

	public static String bitmapToBase64(Bitmap bitmap) {
		Log.e("--bitmapToBase64--","start");
		String result = null;
		ByteArrayOutputStream baos = null;
		try {
			if (bitmap != null) {
				baos = new ByteArrayOutputStream();
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
				baos.flush();
				baos.close();
				byte[] bitmapBytes = baos.toByteArray();
				result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (baos != null) {
					baos.flush();
					baos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		Log.e("--bitmapToBase64--","end");
		return result;
	}
}
